<?php
class ArticleGenerateHelper
{
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $templateBody
	 */
	public static function GenerateArticleByTemplate($templateBody)
	{
		//$pattern = '/[!?.;]/';
		//$arr = preg_split($pattern, $templateBody,-1);
		//$ret = '';
		//foreach ($arr as $key=>$val)
		//{
		//	$ret = $ret.' '.self::GenerateLine($val);
		//}
		return self::GenerateLine($templateBody);//$ret;//self::GenerateLine($templateBody);
	}
	
	public static function startsWith($haystack,$needle,$case=true)
	{
		if($case)
		return strpos($haystack, $needle, 0) === 0;

		return stripos($haystack, $needle, 0) === 0;
	}

	public static function endsWith($haystack,$needle,$case=true)
	{
		$expectedPosition = strlen($haystack) - strlen($needle);

		if($case)
		return strrpos($haystack, $needle, 0) === $expectedPosition;

		return strripos($haystack, $needle, 0) === $expectedPosition;
	}
	
	public static function GenerateLine($line)
	{
		$locators = array();
		if(strpos($line,'{') > -1 && strpos($line, '}') > -1)
		{
			$startIndex = 0;
			$endIndex = 0;
			$i = 0;
			while(strpos($line,'{')  > -1 && strpos($line, '}')  > -1)
			{
				if($line{$i} == '{')
				{
					 $startIndex = $i;
                     //locations.Push($startIndex);//add it to stack
                     array_push($locators,$startIndex);
					 $i++;
                     continue;
				}
				if ($line{$i} == '}')
				{
					$endIndex = $i;
					if (count($locators) > 0)
					{
						//$startIndex = locations.Pop();
						$startIndex = array_pop($locators);
					}
					//replace the current match
					$ret = substr($line, 0,$startIndex);//line.Substring(0, startIndex);
					$arr = explode('|',substr($line, $startIndex, $endIndex - $startIndex + 1));//line.Substring(startIndex, endIndex - startIndex + 1).Split(new string[] { '|' },StringSplitOptions.None);
					//new Random(DateTime.Now.Millisecond).Next(0, arr.Length - 1)
					$random = $arr[rand(0, count($arr) - 1)];

//					if($random == '0')
//					{
//						echo $random;
//					}
					//StartsWith(GlobalSetting.leftBigBracket)
					if (self::startsWith($random,'{',false)) $random = substr($random, 1);// random.Substring(2);

					//EndsWith(GlobalSetting.rightBigBracket)
					if (self::endsWith($random,'}', false)) $random = substr($random, 0, strlen($random) - 1);//random.Substring(0, random.Length - 2);

//					if($random == '0')
//					{
//						echo $random;
//					}
//					
					$ret = $ret.$random;

					$ret = $ret.substr($line,$endIndex + 1);//.Substring(endIndex + 1

					$line = $ret;//.' ';

//					if($line == '0')
//					{
//						echo $line;
//					}
					$i = 0;

					continue;
				}
				$i++;
			}
		}
		return $line;	
	}
}